﻿var me = this,
    vm = this.lookupViewModel(),
    width = 650;

var controller = this.lookupController();
var ukCrossCharge = ref.UKCrossCharge.getValue();

controller.balance = controller.balance || {};
controller.budgetControl = controller.budgetControl || {};

var sharingPrinciple = ref.SharingPrinciple;
if (!sharingPrinciple.hidden && !sharingPrinciple.getValue()) {
    controller.showMsgTips('Company SharingPrinciple is mandatory!');
    return false;
}

var paList = vm.get('NebulogyForm.ProjectActivityList') || [];
var columns = grid.getColumns();
var vendorCodeList = Ext.pluck(ref.datagrid1.store.data.items, 'data');

//Project Activity数据
var paData = [],
    vcData = [];

Ext.each(paList, function (pa) {
    paData.push({
        value: pa.ProjectActivity,
        name: pa.ProjectActivity
    });
});

//Vendor Code 数据
if (vendorCodeList) {

    Ext.each(vendorCodeList, function (vc) {
        vcData.push({
            value: vc.Code,
            name: vc.Code,
            _name: vc.Name
        });
    });
}

var win = Ext.create('Ext.window.Window', {
    title: 'Purchase Items',
    width: width,
    height: 580,
    layout: {
        type: 'float',
        columns: 1
    },
    modal: true,
    cls: 'form-theme landRover',
    items: {
        xtype: 'form',
        layout: 'vbox',
        defaults: {
            labelWidth: 120,
            width: width - 20,
            labelAlign: 'left',
            defaults: {
                labelWidth: 120,
                labelAlign: 'left',
                width: (width - 20) / 2,
                padding: '0 0 10 0',
                allowBlank: false
            }
        },
        items: [{
            fieldLabel: 'Description Of Supplies Services',
            name: 'DescriptionOfSuppliesServices',
            allowBlank: false,
            labelWidth: 220,
            maxLength: 200,
            xtype: 'textfield'
        }, {
            fieldLabel: 'Project Activity',
            name: 'ProjectActivity',
            allowBlank: false,
            editable: false,
            xtype: 'combo',
            queryMode: 'local',
            displayField: 'name',
            valueField: 'value',
            store: paData,
            listeners: {
                select: function (field, record) {

                    controller.getBalance(record.get('value'), null, function () {
                        field.setValue('');
                    });
                }
            }
        }, {
            fieldLabel: 'Vendor Code',
            name: 'VendorCode',
            editable: false,
            allowBlank: true,
            xtype: 'combo',
            queryMode: 'local',
            displayField: 'name',
            valueField: 'value',
            store: vcData,
            listeners: {
                select: function (combo, record) {
                    win.down('hiddenfield[name=VendorName]').setValue(record.get('_name'));
                }
            }
        }, {
            xtype: 'hiddenfield',
            name: 'VendorName'
        }, {
            xtype: 'hiddenfield',
            name: 'materialCode'
        }, {
            fieldLabel: 'Material Group',
            name: 'MaterialGroup',
            xtype: 'paitriggerfield',
            editable: false,
            allowBlank: false,
            listeners: {
                triggerclick: function (trigger, field, e) {

                    var segmentData = [];
                    var Material_Group_NameArr = [];
                    var MGCodeDecsriptionArr = [];
                    //文本框内原本的值
                    var mgValue = field.getValue();

                    //获取Material Group数据.
                    Ext.PAIRest.request({
                        ns: PAI.application.url,
                        url: 'last/materialGroup/page?_dc=' + Date.now(),
                        method: "POST",
                        async: false,
                        data: {},
                        success: function (data) {

                            Ext.each(data.materialGroupList, function (record) {
                                //Segment 数据
                                segmentData.push({
                                    name: record.segment,
                                    value: record.segment
                                });

                                //Segment 数据
                                Material_Group_NameArr.push({
                                    name: record.name,
                                    value: record.name,
                                    segment: record.segment
                                });

                                //Material Group Code & Decsription 数据
                                MGCodeDecsriptionArr.push({
                                    code: record.code,
                                    name: record.code + ' ' + record.description,
                                    value: record.code + ' ' + record.description,
                                    segment: record.segment,
                                    parent: record.name
                                });
                            });
                            var obj = {};
                            segmentData = segmentData.reduce(function (item, next) {
                                obj[next.name] ? '' : obj[next.name] = true && item.push(next);
                                return item;
                            }, []);
                        }
                    });

                    var win = Ext.create('Ext.window.Window', {
                        title: 'Material Group',
                        width: 600,
                        height: 450,
                        modal: true,
                        padding: 10,
                        layout: {
                            type: 'float',
                            columns: 1
                        },
                        cls: 'form-theme landRover',
                        dockedItems: [{
                            xtype: 'toolbar',
                            dock: 'top',
                            items: ['->', {
                                xtype: 'segmentedbutton',
                                width: 300,
                                items: [
                                    { text: 'NPP', name: 'NPP', pressed: true },
                                    { text: 'Tooling', name: 'Tooling' }
                                ],
                                listeners: {
                                    change: function (btn, newValue) {

                                        var Segment = win.down('combo[name=Segment]');
                                        var Material_Group_Name = win.down('combo[name=Material_Group_Name]');
                                        var MGCodeDecsription = win.down('combo[name=MGCodeDecsription]');
                                        var MGCodeDecsriptionForTooling = win.down('combo[name=MGCodeDecsriptionForTooling]');

                                        Segment.setValue('');

                                        Material_Group_Name.setValue('');
                                        Material_Group_Name.setReadOnly(true);

                                        MGCodeDecsription.setValue('');
                                        MGCodeDecsription.setReadOnly(true);

                                        MGCodeDecsriptionForTooling.setValue('');
                                        if (newValue != null) {
                                            Material_Group_Name.hide();
                                            //NPP Click
                                            if (newValue == 0) {
                                                Segment.show();
                                                MGCodeDecsription.show();

                                                MGCodeDecsriptionForTooling.hide();
                                            } else {
                                                Segment.hide();
                                                MGCodeDecsription.hide();

                                                MGCodeDecsriptionForTooling.show();
                                                MGCodeDecsriptionForTooling.setReadOnly(false);
                                                MGCodeDecsriptionForTooling.currentFilter = function (r) {
                                                    return true;
                                                };
                                            }
                                        }
                                    }
                                }
                            }, '->']
                        }],
                        buttonAlign: 'center',
                        buttons: [{
                            text: 'Confirm',
                            handler: function () {
                                var MGCodeDecsription = win.down('combo[name=MGCodeDecsription]');
                                var MGCodeDecsriptionForTooling = win.down('combo[name=MGCodeDecsriptionForTooling]');
                                var npp_tooling = win.down('segmentedbutton').getValue();

                                var mgCtr = npp_tooling == 0 ? MGCodeDecsription : MGCodeDecsriptionForTooling;

                                if (!mgCtr.getValue()) {
                                    mgCtr.focus();
                                } else {
                                    field.setValue(mgCtr.getValue());
                                    win.close();
                                }
                            }
                        }, {
                            text: 'Cancel',
                            handler: function () {
                                win.close();
                            }
                        }],
                        defaults: {
                            width: 580,
                            labelWidth: 200,
                            labelAlign: 'top'
                        },
                        items: [{
                            fieldLabel: 'Segment',
                            name: 'Segment',
                            xtype: 'combo',
                            queryMode: 'local',
                            displayField: 'name',
                            valueField: 'value',
                            store: segmentData,
                            listeners: {
                                change: function (combo, newValue) {

                                    var Material_Group_Name = win.down('combo[name=Material_Group_Name]');
                                    var MGCodeDecsription = win.down('combo[name=MGCodeDecsription]');

                                    var npp_tooling = win.down('segmentedbutton').getValue();
                                    Material_Group_Name.store.clearFilter();
                                    if (npp_tooling == 0) {
                                        MGCodeDecsription.setValue('');
                                        MGCodeDecsription.setReadOnly(false);

                                        MGCodeDecsription.currentFilter = function (r) {
                                            return r.get('segment') == newValue;
                                        };
                                    } else {
                                        Material_Group_Name.setValue('');
                                        Material_Group_Name.setReadOnly(false);

                                        Material_Group_Name.currentFilter = function (r) {
                                            return r.get('segment') == newValue;
                                        };
                                    }
                                }
                            }
                        }, {
                            fieldLabel: 'Material Group Name',
                            name: 'Material_Group_Name',
                            xtype: 'combo',
                            queryMode: 'local',
                            displayField: 'name',
                            valueField: 'value',
                            anyMatch: true,
                            store: new Ext.create('Ext.data.Store', {
                                fields: [
                                    { name: 'name', type: 'string' },
                                    { name: 'value', type: 'string' }
                                ],
                                data: Material_Group_NameArr
                            }),
                            listeners: {
                                select: function (combo, record) {
                                    var MGCodeDecsription = win.down('combo[name=MGCodeDecsription]');

                                    MGCodeDecsription.setValue('');
                                    MGCodeDecsription.setReadOnly(false);

                                    MGCodeDecsription.currentFilter = function (r) {
                                        return r.get('parent') == record.get('value');
                                    };
                                }
                            }
                        }, {
                            fieldLabel: 'Material Group Code & Decsription',
                            name: 'MGCodeDecsription',
                            xtype: 'combo',
                            queryMode: 'local',
                            displayField: 'name',
                            valueField: 'name',
                            anyMatch: true,
                            store: new Ext.create('Ext.data.Store', {
                                fields: [
                                    { name: 'name', type: 'string' },
                                    { name: 'value', type: 'string' }
                                ],
                                data: MGCodeDecsriptionArr
                            }),
                            listeners: {
                                change: setMaterialCode
                            }
                        }, {
                            fieldLabel: 'Material Group Code & Decsription',
                            name: 'MGCodeDecsriptionForTooling',
                            xtype: "combo",
                            hidden: true,
                            displayField: 'name',
                            valueField: 'name',
                            anyMatch: true,
                            store: {
                                type: 'budict',
                                sorters: [{
                                    property: 'orderIndex',
                                    direction: 'DESC'
                                }],
                                code: '2b32ea77-8fb4-4257-8d61-c00ca450a075'
                            },
                            queryMode: "local",
                            listeners: {
                                change: setMaterialCode
                            }
                        }]
                    });
                    win.show();

                    //如果是第二次填写 还需要回写值.
                    if (mgValue) {
                        var Segment = win.down('combo[name=Segment]');
                        var MGCodeDecsription = win.down('combo[name=MGCodeDecsription]');
                        var MGCodeDecsriptionForTooling = win.down('combo[name=MGCodeDecsriptionForTooling]');
                        var npp_tooling = win.down('segmentedbutton');

                        var obj = MGCodeDecsriptionArr.filter(function (obj) {
                            return obj.name == mgValue;
                        });

                        if (obj.length) {
                            MGCodeDecsription.setReadOnly(false);
                            Segment.setValue(obj[0].segment);
                            MGCodeDecsription.setValue(mgValue);
                        } else {
                            npp_tooling.items.items[1].setPressed(true)
                            MGCodeDecsriptionForTooling.setValue(mgValue);
                        }
                        //如果有值 但是值对不上NPP的数据.则就是Tooling的数据字典.
                    }
                }
            }
        }, {
            layout: 'hbox',
            items: [{
                fieldLabel: 'Quantity',
                name: 'Quantity',
                xtype: 'numberfield',
                format: '0,000.00',
                minValue: 1,
                listeners: {
                    change: setNetAmount
                }
            }, {
                fieldLabel: 'Unit Price(Exclude Tax)',
                name: 'UnitPrice',
                xtype: 'numberfield',
                minValue: 1,
                labelWidth: 160,
                format: '0,000.00',
                listeners: {
                    change: setNetAmount
                }
            }]
        }, {
            fieldLabel: 'Net Amount(Exclude Tax)',
            name: 'TotalPrice',
            labelWidth: 200,
            xtype: 'textfield',
            readOnly: true
        }, {
            layout: 'hbox',
            items: [{
                fieldLabel: 'Tax Rate',
                name: 'TaxRate',
                xtype: 'combo',
                anyMatch: true,
                forceSelection: true,
                displayField: 'name',
                valueField: 'code',
                store: {
                    type: 'budict',
                    sorters: [{
                        property: 'orderIndex',
                        direction: 'DESC'
                    }],
                    code: '3e345e97-d8e7-4dc6-a507-c00ec6d349bb'
                },
                editable: false,
                queryMode: "local",
                listeners: {
                    change: function (field, newValue) {
                        var grossAmount = win.down('textfield[name=GrossAmount]');
                        var totalPrice = win.down('textfield[name=TotalPrice]').getValue().replace(/,/g, '');

                        if (totalPrice) {

                            grossAmount.setValue(Ext.util.Format.number(parseFloat((totalPrice * (1 + parseFloat(newValue))).toFixed(2)), '0,000.00'));
                        }
                    }
                }
            }, {
                fieldLabel: 'Gross Amount',
                name: 'GrossAmount',
                xtype: 'textfield',
                readOnly: true
            }]
        }, {
            fieldLabel: 'Specification/Quality Standard',
            name: 'Specification/QualityStandard',
            xtype: 'textfield',
            labelWidth: 220
        }, {
            xtype: 'textfield',
            fieldLabel: 'Comments',
            name: 'Comments'
        }]
    },
    buttons: [{
        xtype: "button",
        text: "Confirm",
        handler: function () {
            var form = win.down('form');
            var data = form.getValues();

            if (form.isValid()) {
                var store = grid.getStore();
                var isExists = false;
                for (var i = 0; i < store.getCount(); i++) {
                    var descriptionOfSuppliesServiceInfo = store.getAt(i).data.DescriptionOfSuppliesServices;
                    if (descriptionOfSuppliesServiceInfo == data.DescriptionOfSuppliesServices) {
                        isExists = true;
                        break;
                    }
                }

                if (isExists) {
                    controller.showMsgTips('Description Of Supplies Services Already exist！');
                    return;
                }
                data.GrossAmount = data.GrossAmount.replace(/,/g, '');
                store.add(data);
                win.close();
                var obj = {
                    name: data.DescriptionOfSuppliesServices,
                    code: data.DescriptionOfSuppliesServices
                }

                //自动生成Company Allocation 数据
                if (ukCrossCharge == 'No' || ukCrossCharge == 'UKJLRC') {
                    autoData(data);
                }

                if (ukCrossCharge != 'PX' && ukCrossCharge != 'Horizon') {
                    var _store4 = ref.datagrid4.getStore();

                    var brandAllocationData = [{
                        ProjectActivity: data.ProjectActivity,
                        test: data.DescriptionOfSuppliesServices
                    }];
                    func(_store4, brandAllocationData, true);
                }

                ref.datagrid3.getColumns()[0].getEditor().store.add(obj);

                if (ref.CompanyAllocation.hidden) {
                    ref.datagrid4.getColumns()[0].getEditor().store.add(obj);
                }
                ref.datagrid6.getColumns()[0].getEditor().store.add(obj);
                ref.horizonGrid.getColumns()[0].getEditor().store.add(obj);


                var amoutCount = [];

                Ext.each(store.data.items, function (record) {
                    amoutCount.push(record.get('TotalPrice'));
                });

                if (amoutCount.length) {
                    ref.pi1.setValue(Ext.util.Format.number(parseFloat(amoutCount.reduce(function (a, b) {
                        return (a + b);
                    }).toFixed(2)), '0,000.00'));
                } else {
                    ref.pi1.setValue('0.00');
                }
            }
        }
    }, {
        xtype: "button",
        text: "Cancel",
        handler: function () {
            win.close();
        }
    }]
});

win.show();

function setNetAmount(field, newValue) {
    var quantityValue = win.down('numberfield[name=Quantity]').getValue();
    var unitPriceValue = win.down('numberfield[name=UnitPrice]').getValue();
    var totalPrice = win.down('textfield[name=TotalPrice]');
    var taxRate = win.down('combo[name=TaxRate]').getValue();

    if (quantityValue && unitPriceValue) {
        var price = parseFloat((quantityValue * unitPriceValue).toFixed(2))
        totalPrice.setValue(Ext.util.Format.number(price, '0,000.00'));

        if (taxRate) {
            var grossAmount = win.down('textfield[name=GrossAmount]');

            grossAmount.setValue(Ext.util.Format.number(parseFloat((price * (1 + parseFloat(taxRate))).toFixed(2)), '0,000.00'));
        }
    }
}

function autoData(record) {
    var expenseType = ref.ExpenseType.getValue();
    //获取SharingPrinciple 控件,如果是隐藏的就默认赋值JLRC 100%数据.
    var sharingPrinciple = ref.SharingPrinciple;
    var companyAllocationData = [];

    var company = ref.companyC.getValue();

    //FME/OUV/Tooling, UK cross charge = NO 公司分摊只有JLRC;
    var isFME_OUV_Tooling = ['1', '4', '5'].includes(expenseType) && ukCrossCharge == 'No';

    if (sharingPrinciple.hidden) {

        if (isFME_OUV_Tooling || company == 'LRE') {
            companyAllocationData.push({
                DescriptionOfSuppliesServices: record.DescriptionOfSuppliesServices,
                ProjectActivity: record.ProjectActivity,
                Company: company,
                CompanySharingRatio: 100,
                Cost: record.TotalPrice,
                originalTotalPrice: record.TotalPrice,
                Balance: controller.balance[record.ProjectActivity],
                budgetControl: controller.budgetControl[record.ProjectActivity],
                isAutoGenerate: true
            });
        } else {
            companyAllocationData.push({
                DescriptionOfSuppliesServices: record.DescriptionOfSuppliesServices,
                ProjectActivity: record.ProjectActivity,
                Company: company,
                CompanySharingRatio: 100,
                Cost: record.TotalPrice,
                originalTotalPrice: record.TotalPrice,
                Balance: controller.balance[record.ProjectActivity],
                budgetControl: controller.budgetControl[record.ProjectActivity],
                isAutoGenerate: true
            });
            companyAllocationData.push({
                DescriptionOfSuppliesServices: record.DescriptionOfSuppliesServices,
                ProjectActivity: record.ProjectActivity,
                Company: 'CJLR',
                CompanySharingRatio: 0,
                Cost: 0,
                originalTotalPrice: 0,
                Balance: 'N/A',
                budgetControl: controller.budgetControl[record.ProjectActivity],
                isAutoGenerate: true
            });
        }
    } else {
        var JLRC, CJLR;

        JLRC = parseInt(sharingPrinciple.getValue().split('|')[0]);
        CJLR = 100 - JLRC;

        companyAllocationData.push({
            DescriptionOfSuppliesServices: record.DescriptionOfSuppliesServices,
            ProjectActivity: record.ProjectActivity,
            Company: 'JLRC',
            CompanySharingRatio: JLRC,
            Cost: (record.TotalPrice * JLRC) / 100,
            originalTotalPrice: (record.TotalPrice * JLRC) / 100,
            Balance: controller.balance[record.ProjectActivity],
            budgetControl: controller.budgetControl[record.ProjectActivity],
            isAutoGenerate: true
        });

        companyAllocationData.push({
            DescriptionOfSuppliesServices: record.DescriptionOfSuppliesServices,
            ProjectActivity: record.ProjectActivity,
            Company: 'CJLR',
            CompanySharingRatio: CJLR,
            Cost: (record.TotalPrice * CJLR) / 100,
            originalTotalPrice: (record.TotalPrice * CJLR) / 100,
            Balance: controller.balance[record.ProjectActivity],
            budgetControl: controller.budgetControl[record.ProjectActivity],
            isAutoGenerate: true
        });
    }

    var _store3 = ref.datagrid3.getStore();

    func(_store3, companyAllocationData);
}

function func(store, data, needUpdate) {
    var dss = data[0].DescriptionOfSuppliesServices || data[0].test;
    //删除的数量等于 新增的数量 所以这里要循环.
    for (var i = 0; i < data.length; i++) {
        //先删除重复的.
        var r = store.findRecord('DescriptionOfSuppliesServices', dss);
        if (r) {
            store.remove(r);
        }
    }

    //在新增.
    for (var j = 0; j < data.length; j++) {
        store.add(data[j]);
    }
    if (needUpdate) {
        setTimeout(function () {
            for (var j = 0; j < store.data.items.length; j++) {
                var currData = store.data.items[j];
                if (dss == currData.get('test')) {
                    currData.set('DescriptionOfSuppliesServices', dss);
                }
            }
        }, 200);
    }
}

function setMaterialCode(field) {
    var record = field.getSelectedRecord();
    if (record) {
        win.down('hiddenfield[name=materialCode]').setValue(record.get('code'));
    }
}

return false;